# code a function to estimate the effect of an event:
estim_diff <- function(event_name, d, dep.var = "abn_chg", type_count = "lasso"){
  e <- d[,event_name] %>% pull() %>% unique()
  
  if (dep.var == "chg") {
    dv <- "chg"
  } else {
    dv <- paste0(dep.var, '_', type_count, '_', event_name)
  }
  
  d <- d %>% filter(date == e)
  
  v_fos <- d[d$sample == "Fossil fuel", dv] %>% pull()
  v_ren <- d[d$sample != "Fossil fuel", dv] %>% pull()
  
  t_fos <- v_fos %>%
    t.test()
  
  t_ren <- v_ren %>%
    t.test()
  
  out <- t_fos %>%
    broom::tidy() %>%
    mutate(sample = "Fossil fuel",
           size = sum(!is.na(v_fos)),
           std.err = t_fos$stderr) %>%
    rbind(t_ren %>%
            broom::tidy() %>%
            mutate(sample = "Renewable energy",
                   size = sum(!is.na(v_ren)),
                   std.err = t_fos$stderr))
  
  # test for difference:
  diff <- t.test(v_fos, v_ren)
  
  out$diff.est <- (diff$estimate[2]-diff$estimate[1]) %>% as.vector()
  out$diff.pval <- diff$p.value
  out$diff.c.lo <- diff$conf.int[1]
  out$diff.c.hi <- diff$conf.int[2]
  
  out <- out %>%
    mutate(event = event_name,
           date = e,
           dv = dv)
  
  return(out)
}

estim_car_diff <- function(event_name, d, size = 10, type_count = "lasso"){
  e <- d[,event_name] %>% pull() %>% unique()
  
  # fix the data and compute CARs:
  abn_chg <- paste0("abn_chg_", type_count, "_", event_name)
  dat <- d %>%
    filter(date >= e - size &
             date <= e + size) %>%
    mutate(event = case_when(date >= e ~ 1,
                             TRUE ~ 0)) %>%
    select(ticker, date, sample, event, all_of(abn_chg)) %>%
    rename("abn_chg" = all_of(abn_chg)) %>%
    group_by(ticker) %>%
    arrange(ticker, date) %>%
    mutate(dep.var = cumsum(tidyr::replace_na(abn_chg, 0)))
  
  mod <- feols(dep.var ~ event*sample,
               data = dat,
               cluster = ~ticker)
  out <- avg_slopes(mod, variables = c("event"), by = "sample") %>%
    broom::tidy() %>%
    select(term, sample, estimate, std.error, statistic, p.value, conf.low, conf.high)
  
  br <- broom::tidy(mod, conf.int = TRUE) %>%
    filter(term == "event:sampleRenewable energy")
  
  out$diff.est <- br$estimate %>% as.vector()
  out$diff.pval <- br$p.value %>% as.vector()
  out$diff.c.lo <- br$conf.low %>% as.vector()
  out$diff.c.hi <- br$conf.high %>% as.vector()
  
  out <- out %>%
    left_join(dat %>%
                filter(!is.na(dep.var) & !is.na(event) & !is.na(sample)) %>%
                group_by(sample) %>%
                reframe(N = n(),
                        N_clusters = length(unique(ticker))),
              by = "sample")
  
  
  out <- out %>%
    mutate(event = event_name,
           date = e)
  
  return(out)
}